package com.wits.comet.chat.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wits.comet.chat.entity.ChatMember;
import com.wits.comet.chat.service.ChatRoomService;
import com.wits.comet.chat.service.CometContext;
import com.wits.comet.chat.service.CurrentLoginUser;
import com.wits.platform.service.account.ShiroUser;
import com.wits.platform.web.controller.BaseController;

@Controller
@RequestMapping(value="qso/comet")
public class CometController extends BaseController{
	
	@Autowired
	private ChatRoomService chatRoomService;
	
	
//	/** 默认超时时间     默认30分钟   **/
//	private long timeout = 1800000;
	/** 默认超时时间     8小时   **/
	private long timeout = 28800000;
	
	
    private static final String JUNK = "<!-- Comet is a programming technique that enables web " +
            "servers to send data to the client without having any need " +
            "for the client to request it. -->\n";
    
	@RequestMapping(value="/saveAsync")
	public void saveAsync(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException{
        res.setContentType("text/html");
        res.setHeader("Cache-Control", "private");
        res.setHeader("Pragma", "no-cache");
        PrintWriter writer = res.getWriter();
        // for Safari, Chrome, IE and Opera
        for (int i = 0; i < 10; i++) {
            writer.write(JUNK);
        }
        writer.flush();
		final ShiroUser shiroUser=this.getCurrentUser();
		final AsyncContext ac = req.startAsync(req, res);

		ac.setTimeout(this.timeout);
		ac.addListener(new AsyncListener() {
			public void onComplete(AsyncEvent event) throws IOException {
				//chatRoomService.logout(shiroUser);
			}
			public void onTimeout(AsyncEvent event) throws IOException {
				chatRoomService.logout(shiroUser);
			}
			public void onError(AsyncEvent event) throws IOException {
				chatRoomService.logout(shiroUser);
			}
			public void onStartAsync(AsyncEvent event) throws IOException {
			}
		});
		CurrentLoginUser.getInstance().addMember(shiroUser);
		chatRoomService.login(shiroUser,ac);
	}

}
